package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    //注入jedispool
    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }


    /**
     * 分页查询
     */
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){

        try {
            Integer pageSize = queryPageBean.getPageSize();
            Integer currentPage = queryPageBean.getCurrentPage();
            String queryString = queryPageBean.getQueryString();

            PageResult pageResult = userService.findPage(currentPage, pageSize, queryString);

            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,pageResult);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 新增用户
     */
    @RequestMapping("/add")
    public Result addUser(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){

        try {
            userService.saveUser(user,roleIds);
            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }

    }

    /**
     * 编辑回显用户数据
     */
    @RequestMapping("/findByUserId")
    public Result getById(Integer id){
        try {
            com.itheima.pojo.User user = userService.findById(id);
            return   new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }

    }

    /**
     * 编辑回显用户角色
     */
    @RequestMapping("/findRoleByUserId")
    public Result findRoleByUserId(Integer id){

        try {
            Integer[] roleIdsByUserId = userService.findRoleIdsByUserId(id);
            return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,roleIdsByUserId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ROLE_FAIL);
        }

    }
    /**
     * 编辑提交数据
     */
    @RequestMapping("/update")
    public Result updateUser(@RequestBody com.itheima.pojo.User user, Integer [] roleIds){
        try {
            userService.updateUser(user,roleIds);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }
    //删除用户
    @RequestMapping("/delete")
    public  Result deleteUser( Integer id){
        try {
            userService.deleteUser(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }

    /**
     * 修改用户状态
     * @param userId
     * @param station
     * @return
     */
    @RequestMapping("/updateStation")
    public Result updateStation(Integer userId,Integer station){
        try {
            userService.updateStation(userId,station);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }


            @RequestMapping("submit")
            public Result submit(@RequestBody Map map) {
                //获取参数
                String telephone = (String) map.get("telephone");
                String validateCode = (String) map.get("validateCode");
                String password01 = (String) map.get("password01");
                String password02 = (String) map.get("password02");
                //从Redis中获取保存的验证码
                String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
                if (validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)) {
                    if (password01.equals(password02)) {
                        com.itheima.pojo.User user = userService.findByTelephone(telephone);
                        if (user != null) {
                            userService.updatePassword(user.getId(), password01);
                            return new Result(true, "密码修改成功,2秒钟后跳转登录页面");
                        } else {
                            return new Result(false, "请检查电话号码是否正确");
                        }
                    } else {
                        return new Result(false, "请确认密码是否相同");
                    }

                } else {
                    return new Result(false, "验证码错误");
                }

            }



@RequestMapping("/findHealth")
            public Result findHealth(){
                try {
       List<com.itheima.pojo.User>  user=userService.findHealth();
                    return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
                }catch (Exception e){
                    e.printStackTrace();
                    return new Result(false,MessageConstant.QUERY_USER_FAIL);
                }
            }

    @RequestMapping("/getUserImg")
    public Result getUserImg(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user != null){
            String username = user.getUsername();
            String img = userService.findImg(username);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,img);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }


}
